from PyQt5.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QScrollArea, QLabel, QComboBox,
    QStatusBar, QMenuBar, QAction, QMessageBox,
    QSplitter, QFrame
)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon, QFont
from models.task import Priority, TaskStatus
from models.task_manager import TaskManager
from utils.storage import Storage
from .task_dialog import TaskDialog
from .task_item import TaskItem


class MainWindow(QMainWindow):
    """主窗口"""
    
    def __init__(self):
        super().__init__()
        self.task_manager = TaskManager()
        self.storage = Storage()
        self.task_items = {}  # 存储任务项组件
        
        self.init_ui()
        self.setup_menu()
        self.setup_connections()
        self.load_data()
        self.update_task_list()
        self.update_status_bar()
        
        # 自动保存定时器
        self.auto_save_timer = QTimer()
        self.auto_save_timer.timeout.connect(self.save_data)
        self.auto_save_timer.start(30000)  # 每30秒自动保存
    
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("Todo 应用")
        self.setGeometry(100, 100, 800, 600)
        
        # 中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout()
        
        # 顶部工具栏
        toolbar_layout = QHBoxLayout()
        
        # 添加任务按钮
        self.add_button = QPushButton("添加任务")
        self.add_button.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)
        toolbar_layout.addWidget(self.add_button)
        
        toolbar_layout.addStretch()
        
        # 筛选器
        filter_label = QLabel("筛选:")
        toolbar_layout.addWidget(filter_label)
        
        self.filter_combo = QComboBox()
        self.filter_combo.addItems(["全部", "待完成", "已完成"])
        self.filter_combo.setMinimumWidth(100)
        toolbar_layout.addWidget(self.filter_combo)
        
        # 优先级筛选
        priority_label = QLabel("优先级:")
        toolbar_layout.addWidget(priority_label)
        
        self.priority_filter_combo = QComboBox()
        self.priority_filter_combo.addItems(["全部", "高", "中", "低"])
        self.priority_filter_combo.setMinimumWidth(80)
        toolbar_layout.addWidget(self.priority_filter_combo)
        
        # 清除已完成按钮
        self.clear_completed_button = QPushButton("清除已完成")
        self.clear_completed_button.setStyleSheet("""
            QPushButton {
                background-color: #ff6b6b;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #ff5252;
            }
        """)
        toolbar_layout.addWidget(self.clear_completed_button)
        
        main_layout.addLayout(toolbar_layout)
        
        # 分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        main_layout.addWidget(separator)
        
        # 任务列表区域
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        
        # 任务列表容器
        self.task_list_widget = QWidget()
        self.task_list_layout = QVBoxLayout()
        self.task_list_layout.setSpacing(5)
        self.task_list_layout.addStretch()
        self.task_list_widget.setLayout(self.task_list_layout)
        
        self.scroll_area.setWidget(self.task_list_widget)
        main_layout.addWidget(self.scroll_area)
        
        central_widget.setLayout(main_layout)
        
        # 状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
    
    def setup_menu(self):
        """设置菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu('文件')
        
        # 保存动作
        save_action = QAction('保存', self)
        save_action.setShortcut('Ctrl+S')
        save_action.triggered.connect(self.save_data)
        file_menu.addAction(save_action)
        
        # 备份动作
        backup_action = QAction('备份数据', self)
        backup_action.triggered.connect(self.backup_data)
        file_menu.addAction(backup_action)
        
        file_menu.addSeparator()
        
        # 退出动作
        exit_action = QAction('退出', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu('帮助')
        
        # 关于动作
        about_action = QAction('关于', self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
    
    def setup_connections(self):
        """设置信号连接"""
        self.add_button.clicked.connect(self.add_task)
        self.filter_combo.currentTextChanged.connect(self.update_task_list)
        self.priority_filter_combo.currentTextChanged.connect(self.update_task_list)
        self.clear_completed_button.clicked.connect(self.clear_completed_tasks)
    
    def add_task(self):
        """添加新任务"""
        task_data = TaskDialog.add_task(self)
        if task_data:
            task = self.task_manager.add_task(
                task_data['title'],
                task_data['description'],
                task_data['priority']
            )
            self.update_task_list()
            self.update_status_bar()
            self.save_data()
    
    def edit_task(self, task_id: str):
        """编辑任务"""
        task = self.task_manager.get_task(task_id)
        if task:
            task_data = TaskDialog.edit_task(self, task)
            if task_data:
                self.task_manager.update_task(
                    task_id,
                    task_data['title'],
                    task_data['description'],
                    task_data['priority']
                )
                self.update_task_list()
                self.update_status_bar()
                self.save_data()
    
    def delete_task(self, task_id: str):
        """删除任务"""
        task = self.task_manager.get_task(task_id)
        if task:
            reply = QMessageBox.question(
                self, '确认删除',
                f'确定要删除任务 "{task.title}" 吗？',
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                self.task_manager.delete_task(task_id)
                self.update_task_list()
                self.update_status_bar()
                self.save_data()
    
    def toggle_task(self, task_id: str):
        """切换任务状态"""
        self.task_manager.toggle_task_status(task_id)
        self.update_task_list()
        self.update_status_bar()
        self.save_data()
    
    def clear_completed_tasks(self):
        """清除已完成任务"""
        completed_count = len(self.task_manager.get_completed_tasks())
        if completed_count == 0:
            QMessageBox.information(self, '提示', '没有已完成的任务需要清除。')
            return
        
        reply = QMessageBox.question(
            self, '确认清除',
            f'确定要清除 {completed_count} 个已完成的任务吗？',
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            cleared_count = self.task_manager.clear_completed_tasks()
            self.update_task_list()
            self.update_status_bar()
            self.save_data()
            QMessageBox.information(self, '完成', f'已清除 {cleared_count} 个已完成的任务。')
    
    def update_task_list(self):
        """更新任务列表"""
        # 清除现有任务项
        for task_item in self.task_items.values():
            task_item.setParent(None)
        self.task_items.clear()
        
        # 清除布局中的所有组件（除了最后的stretch）
        while self.task_list_layout.count() > 1:
            child = self.task_list_layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()
        
        # 获取筛选后的任务
        tasks = self.get_filtered_tasks()
        
        # 按创建时间排序（最新的在前）
        tasks.sort(key=lambda t: t.created_at, reverse=True)
        
        # 创建任务项
        for task in tasks:
            task_item = TaskItem(task)
            task_item.task_toggled.connect(self.toggle_task)
            task_item.task_edit_requested.connect(self.edit_task)
            task_item.task_delete_requested.connect(self.delete_task)
            
            self.task_items[task.id] = task_item
            # 插入到布局中（在stretch之前）
            self.task_list_layout.insertWidget(
                self.task_list_layout.count() - 1, task_item
            )
        
        # 如果没有任务，显示提示
        if not tasks:
            no_tasks_label = QLabel("暂无任务")
            no_tasks_label.setAlignment(Qt.AlignCenter)
            no_tasks_label.setStyleSheet("color: #999; font-size: 16px; padding: 50px;")
            self.task_list_layout.insertWidget(
                self.task_list_layout.count() - 1, no_tasks_label
            )
    
    def get_filtered_tasks(self):
        """获取筛选后的任务列表"""
        # 状态筛选
        filter_text = self.filter_combo.currentText()
        if filter_text == "待完成":
            tasks = self.task_manager.get_pending_tasks()
        elif filter_text == "已完成":
            tasks = self.task_manager.get_completed_tasks()
        else:
            tasks = self.task_manager.get_all_tasks()
        
        # 优先级筛选
        priority_filter = self.priority_filter_combo.currentText()
        if priority_filter != "全部":
            priority = Priority(priority_filter)
            tasks = [task for task in tasks if task.priority == priority]
        
        return tasks
    
    def update_status_bar(self):
        """更新状态栏"""
        stats = self.task_manager.get_task_count()
        status_text = f"总计: {stats['total']} | 待完成: {stats['pending']} | 已完成: {stats['completed']}"
        self.status_bar.showMessage(status_text)
    
    def save_data(self):
        """保存数据"""
        data = self.task_manager.to_dict()
        if self.storage.save(data):
            self.status_bar.showMessage("数据已保存", 2000)
        else:
            QMessageBox.warning(self, '错误', '保存数据失败！')
    
    def load_data(self):
        """加载数据"""
        data = self.storage.load()
        self.task_manager.from_dict(data)
    
    def backup_data(self):
        """备份数据"""
        if self.storage.backup():
            QMessageBox.information(self, '成功', '数据备份成功！')
        else:
            QMessageBox.warning(self, '错误', '数据备份失败！')
    
    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(
            self, '关于',
            'Todo 应用\n\n'
            '一个简单而强大的任务管理工具\n'
            '使用 PyQt5 开发\n\n'
            '功能特性：\n'
            '• 添加、编辑、删除任务\n'
            '• 任务优先级管理\n'
            '• 任务状态筛选\n'
            '• 数据自动保存\n'
            '• 数据备份功能'
        )
    
    def closeEvent(self, event):
        """关闭事件"""
        # 保存数据
        self.save_data()
        event.accept()